<template>
    <div class='content'>
        <div class="profile_page">
                <head-top  :go-back='goBack'  :head-title="profiletitle"></head-top>
        </div>
        <div class="formContain">
            <titlebar :title-left='titleLeft'></titlebar>
            <ul>
                <li class="flex">
                    <span class="label"><i class="require">*</i>开始时间</span>
                    <div @click="showdatepicker($event,'startTime')">
                        <input type="text"  id="begin" placeholder="请选择时间" :value="datas.startTime"  readonly>
                        <img src="@/assets/images/img/calendarIcon.png" alt="" srcset="" >
                    </div>
                </li>
                 <li class="flex">
                    <span class="label"><i class="require">*</i>结束时间</span>
                    <div @click="showdatepicker($event,'endTime')">
                        <input type="text"  id="end" placeholder="请选择时间" :value="datas.endTime"  readonly>
                        <img src="@/assets/images/img/calendarIcon.png" alt="" srcset="" >
                    </div>
                </li>
                 <li class="flex">
                    <span class="label"><i class="require">*</i>请假类型</span>
                    <div @click="showpicker($event,'leaveNames','请假类型')">
                        <input type="text"  id="type" placeholder="请选择请假类型" :value="datas.leaveNames.text"  readonly>
                        <input type="hidden"  id="type1" placeholder="请选择请假类型" :value="datas.leaveNames.id" >
                        <span class="iconfont icon-xiala"></span>
                    </div>
                </li>
                  <li class="flex">
                    <span class="label"><i class="require">*</i>请假时长（天）</span>
                    <div>
                      <div class="van-cell van-field number-input">
                        <div class="van-cell__value van-cell__value--alone">
                          <div class="van-field__body">
                            <MyNumberInput :point="1" :max="999999" placeholder="请输入天数" v-model.number="datas.leaveAmount"></MyNumberInput>
                          </div>
                        </div>
                      </div>
                        <!--<van-field v-model="datas.leaveAmount" @input="checkNum" maxlength="6" placeholder="请输入天数" type="number" step="0.1" input-align="right"/>-->
                    </div>
                </li>
                 <li class="flex" v-if="company !== 'W'">
                    <span class="label">剩余年假</span>
                    <div>
                      <div class="van-cell van-field number-input">
                        <div class="van-cell__value van-cell__value--alone">
                          <div class="van-field__body">
                            <MyNumberInput :point="1" :max="999999" placeholder="请输入天数" readonly v-model.number="datas.annualLeave"></MyNumberInput>
                          </div>
                        </div>
                      </div>
                    </div>
                </li>
            </ul>

        </div>
         <div class="formContain">
            <titlebar :title-left='titleLeft1'></titlebar>
            <ul>
                <li class="flex">
                    <div class='full_width' style="min-height:2rem">
                        <i class="require">*</i>
                        <van-field class='full_width'  rows="1" autosize v-model="datas.remark" placeholder="请输入请假原因" type="textarea" input-align="left"/>
                    </div>
                </li>
                <li class="flex">
                    <span class="label">上传附件</span>
                    <div>
                      <!-- <input class="file" type="file"  id="fileExport" @change="handleFileChange" ref="inputer"  readonly> -->
                      <input type="text" v-model="fileName" disabled style="background: transparent;width: 10rem;position: absolute;padding-right: 1rem">
                      <van-uploader :after-read="afterRead" :before-read="beforeRead" id="file">
                        <span class="iconfont icon-hao"></span>
                    </van-uploader>
                     <!-- <input class="file" type="file"  id="file" accept="image/*"  readonly>
                      <span class="iconfont icon-hao"></span>-->
                    </div>
                </li>
            </ul>
         </div>
         <div class="align_center foot-button" >
              <van-button class="cancel-btn" type="primary" @click="$router.go(-1)">取消</van-button>
            <van-button class="primary-btn" type="primary" @click="saveLeaveData">提交</van-button>
         </div>
        <van-picker id="picker"   show-toolbar  :title="title" v-show='pickershow' :columns="columns" @cancel="onCancel" @confirm="onConfirm"/>
        <van-datetime-picker v-show='show' id="datetime-picker" type="datetime" @confirm="datetimeSelect" @cancel='cancel' v-model="currentTime"/>
    </div>
</template>

<script>
    import headTop from '@/components/header/head'
     import titlebar from '@/components/titlebar3/titlebar3';
    import {canSave,startProcess,annualLeave,uploadFile,saveLeave,annualTypes,processInstance,sysTime} from '@/service/getData';
    import {getStore,getDefault} from '@/assets/config/mUtils';
    import { Dialog,Toast} from 'vant';
    import MyNumberInput from '@/components/numberInput/numberInput';
    import {getUser} from '@/service/getData';
    export default {
    	data(){
            return{
                company:"",//所属公司
                profiletitle:'请假',
                goBack:true,
                titleLeft:'请假信息',
                titleLeft1:'请假原因',
                show:false, //控制日期显示隐藏
                pickershow:false,//控制下拉选显示隐藏
                pickerName:'',//当前控制日期的控件
                currentTime:new Date(),
                fileName:'',
                datas:{
                  endTime:'',
                  startTime:'',
                  leaveNames:'',
                  leaveAmount:'',
                  annualLeave:'',
                  remark:'',
                  attachmentId:"",
                  annualYear:''
                },
              screenHeight:'',
              startManagerId:'',
              bussinessTable:'ACT_ATND_LEAVE',
               title:'标题',//下拉框标题
              columns: []  //下拉框数据
            }
        },
        created(){
          var processData = {};
          processData.processDefinitionKey = 'leaveTheProcess';
          processData.app_userId = getStore('user_id');
          processData.CHECK_TIME = new Date().getTime().toString();
          processData.CHECK_SIGN = this.$md5(processData.app_userId + processData.CHECK_TIME +"3a28fba00c015e0df7f88556c91cb7fc");
         // processData = JSON.stringify(processData);
          startProcess(processData).then(res=>{
            console.log(res);
            this.startManagerId = res.data.startManagerId;
          });
          var data = getDefault();
          sysTime(data).then(res=>{
            this.datas.annualYear = res.data.substring(0,4);
          })

          // 判断是不是物业，物业不加载判断年假
          getUser(data).then(res=>{
            this.company = res.data.appPersonVo.company;
            console.log(this.company);
          })
        },
        mounted(){
    	  const _self = this;
          this.screenHeight = document.documentElement.clientHeight;
          var data = getDefault();
          annualLeave(data).then(res =>{
            this.datas.annualLeave = res.data.annualRemainDays || 0;
          });
          // let delIndex = 0;
          annualTypes(data).then(res=>{
            //
            var vacnLeave = res.data.vacnLeaves;
            for(var i=0;i<vacnLeave.length;i++){
              for(var key in vacnLeave[i]){
                if(key == "leaveName"){
                  vacnLeave[i]["text"]= vacnLeave[i][key];
                  delete vacnLeave[i][key];
                }
              }
            };
            this.columns = vacnLeave;
          })

          // test1();
      //     function takeLongTime() {
      //     return  annualTypes().then(res=>{
      //         return res
      //       })
      //   }
      //   var v
      //   async function test() {
      //        v = await takeLongTime();
      //         console.log(v);
      //         return v;
      //   }

      //  var a = test();
      //  console.log(a)
        },
        components:{
            headTop,
            titlebar,
          MyNumberInput
        },
      updated () {
        let that = this;
        this.$nextTick(function () {
          let $inputs = Array.from(document.getElementsByTagName('input'));
          /*let body = document.body;
          $inputs.forEach(item => { // 定时器是处理多个input间快速切换闪屏问题，可省略
              item.onblur = function () { // onblur是核心方法
                  clearTimeout(body.timer);
                  body.timer = setTimeout(() => {
                  window.scroll(0, 0);
                  window.innerHeight = window.outerHeight = that.screenHeight
                  }, 150)
              }
              item.onfocus = function () {
                  clearTimeout(body.timer)
              }
          })*/
          let body = document.body;
          $inputs.forEach(item => {
            item.onblur = function () { // onblur是核心方法
              window.scroll(0, 0);
              window.innerHeight = window.outerHeight = that.screenHeight;
              //console.log(that.screenHeight);
            }
          })
        })
      },
        methods:{
            // checkNum(){
            //   this.datas.leaveAmount = parseFloat(this.datas.leaveAmount)
            // },
            datetimeSelect(value){
                this.show = false;
                var date = value;
              var val = date.getFullYear() + '-'+this.addZero(date.getMonth()+1) + '-'+ this.addZero(date.getDate())+' '+this.addZero(date.getHours()) + ':'+ this.addZero(date.getMinutes());

              this.$set(this.datas,this.pickerName,val);
              if(this.datas.endTime != ""){
                if(this.datas.startTime >= this.datas.endTime){
                  Dialog.alert({
                    title: '',
                    message: '开始时间不能大于结束时间'
                  });
                  this.datas.endTime = '';
                }
              };

                // document.getElementById(this.pickerName).value = val;
              /*if(this.datas.startTime!=''&& this.datas.endTime!= ''){
                this.datas.leaveAmount = this.leaveAmount(this.datas.startTime, this.datas.endTime);
              }*/
            },
            beforeRead(file) {
              var imgType = file.type.toLocaleLowerCase();
              if (imgType != 'image/jpg'&&imgType != 'image/jpeg'&&imgType != 'image/png'&&imgType != 'image/gif'&&imgType != 'image/bmp') {
                Toast('请上传图片');
                return false;
              }

              return true;
            },
             afterRead(file) {
                // 此时可以自行将文件上传至服务器
                console.log(file.file.name);
               Toast.loading({
                 duration: 0,   // 持续展示 toast
                 mask: true,
                 message: '正在上传...'
               });
               var formData = new FormData();
            formData.append("uploadFile", file.file);
              uploadFile(formData).then(res=>{
                this.fileName = file.file.name;
                console.log(res);
                this.datas.attachmentId = res.fileId;
                Toast.clear();
              })
              },
            onConfirm(value){
              console.log(this.datas);
              this.$set(this.datas,this.pickerName,value);
               this.pickershow = false;
            },
            cancel() {
                this.show = false;
            },
            onCancel(){
                this.pickershow = false;
            },
            showdatepicker(event,name){
                this.show = true;
                this.pickerName = name;
            },
            showpicker(event,name,title){
                this.pickershow = true;
                this.pickerName = name;
                this.title = title;
            },
          addZero(num){
            var addNum = num<10?"0"+num:num;
            return addNum;
          },
            saveLeaveData(){
              Toast.loading({
                duration: 0,   // 持续展示 toast
                mask: true,
                message: '正在提交...'
              });
            if(this.datas.leaveAmount<0.5){
              Toast.clear();
                Dialog.alert({
                  title: '',
                  message: '请假时长最小为0.5天'
                });
              this.datas.leaveAmount = "";
              }else {
              var savaLeaveDatas = this.datas;
              savaLeaveDatas.applyUser = getStore('user_id');
              savaLeaveDatas.app_userId = getStore('user_id');
              savaLeaveDatas.CHECK_TIME = new Date().getTime();
              savaLeaveDatas.CHECK_SIGN = this.$md5(savaLeaveDatas.app_userId + savaLeaveDatas.CHECK_TIME +"3a28fba00c015e0df7f88556c91cb7fc");
              savaLeaveDatas.leaveId = this.datas.leaveNames.id;

              var data = {};
              data.app_userId = getStore('user_id');
              data.processRespondentUserId = getStore('user_id');
              data.processType = "KQ";
              data.day = this.datas.leaveAmount;
              data.CHECK_TIME = new Date().getTime();
              data.CHECK_SIGN = this.$md5(data.app_userId + data.CHECK_TIME +"3a28fba00c015e0df7f88556c91cb7fc");
              data.startManagerId = this.startManagerId;
              data.bussinessTable = this.bussinessTable;
              data.procInstanceIdStatus = "9050000002";
              data.processDefinitionKey = 'leaveTheProcess';
              console.log(data);

              // 判断是否可以提交
              canSave(data).then(res=>{
                if(res.code == 200){
                  if(!res.data.flag){
                    Toast.clear();
                    Dialog.confirm({
                      title: '提示',
                      message: res.data.message
                    }).then(() => {
                      saveLeave(savaLeaveDatas).then(res=>{
                        if(res.code == 200){
                          data.bussinessIds = res.data;
                          processInstance(data).then(res1=>{
                            if(res1.code == 200){
                              Toast.clear();
                              Dialog.alert({
                                title: '提示',
                                message: '提交审批成功'
                              }).then(() => {
                                this.$router.go(-1);
                              });
                            }
                          })
                          /* Dialog.alert({
                             title: '提示',
                             message: '保存成功'
                           }).then(() => {
                             this.$router.go(-1);
                           });*/
                        }else if(res.code==400){
                          Toast.clear();
                          Dialog.alert({
                            title: '提示',
                            message: res.msg
                          })
                        }
                      })
                    }).catch(() => {
                      return false;
                    });
                  }else{
                    saveLeave(savaLeaveDatas).then(res=>{
                      if(res.code == 200){
                        data.bussinessIds = res.data;
                        processInstance(data).then(res1=>{
                          if(res1.code == 200){
                            Toast.clear();
                            Dialog.alert({
                              title: '提示',
                              message: '提交审批成功'
                            }).then(() => {
                              this.$router.go(-1);
                            });
                          }
                        })
                        /* Dialog.alert({
                           title: '提示',
                           message: '保存成功'
                         }).then(() => {
                           this.$router.go(-1);
                         });*/
                      }else if(res.code==400){
                        Toast.clear();
                        Dialog.alert({
                          title: '提示',
                          message: res.msg
                        })
                      }
                    })
                  }
                }else if(res.code==400){
                  Toast.clear();
                  Dialog.alert({
                    title: '提示',
                    message: res.msg
                  })
                }
              })


            }



            },
          handleFileChange(){
            let inputDOM = this.$refs.inputer;
            // 通过DOM取文件数据
            this.file    = inputDOM.files[0];
            console.log(this.file,"文件");
            var fileData = {}
            fileData.fileName =this.file.name;
            this.errText = '';
            let size = Math.floor(this.file.size / 1024);
            //new一个FileReader实例
            let reader = new FileReader();
            let _this = this;
            // reader.readAsText(this.file)  //文本读取，默认utf-8，格式 其他格式：reader.readAsText(this.file, "GBK")
            reader.readAsDataURL(this.file)  //base 64 读取
            reader.onload=function(e){
              // 读取结果
              fileData.fileResult = this.result;
              console.log(fileData);
              uploadFile(fileData).then(res=>{
                console.log(res);
              })
              // if (size > ...) {
              //     // 这里可以加个文件大小控制
              //     return false
              // }
            }

          },
        }
    }

</script>

<style lang="scss" scoped>
    @import '../../assets/style/mixin';
    @import '../../assets/style/public';
    .formContain{
        background: #fff;
        ul{
            padding: 0 .54rem;
            .flex{
                justify-content: space-between;
                align-items: center;
                line-height: 2rem;
                border-bottom: 1px solid #e0e0e0;
                padding: 0 .3rem;
                &:nth-last-of-type(1){
                    border: none;
                }
                .label{
                    font-size: .56rem;
                    line-height: 2rem;
                    color: #333333;
                }
                div{
                    display: flex;
                    justify-content: flex-end;
                    align-items: center;
                    position: relative;
                    flex-grow: 1;
                    img{
                        width: .68rem;
                        height: .64rem;
                    }
                    input{
                        color: #323233;
                        text-align: right;
                        font-size: .48rem;
                        padding-right: .48rem;
                        border: none;
                        &:-ms-input-placeholder{
                             color: #aaa;
                             font-size: .48rem;

                        }
                    }
                    .file{
                        width: 2rem;
                        height: 1rem;
                        font-size: 10rem;
                        opacity: 0;
                        position: absolute;
                        right: 0;
                    }
                    .van-cell{
                        font-size: .48rem;
                        padding-right: .48rem;
                        padding: 0;
                        color: #aaa;
                        .van-field__control{
                            color: #aaa;
                        }
                    }

                }
            }
        }
    }
    .foot-button{
        margin-top: 2rem;
        margin-bottom: .4rem;
        .cancel-btn{
            margin-right: 1rem;
        }
    }
    #datetime-picker,#picker{
        position: fixed;
        width: 100%;
        bottom: 0;
    }
    .require{
      color: red;
      margin-right: 4px;
      font-style: inherit;
      font-size: 14px;
    }
</style>
